package com.xwtec.prototype.v2;

/**
 * @Author: zt
 * @Date: 2021/3/7 17:26
 * 实现原型的方式，深拷贝,拷贝的引用还要再克隆一次
 * 例外一点，深克隆时，不需要对string类型进行深克隆，string在改变时改变的是引用
 */
public class Main {

    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person(8, 100, new Location("bj", 2001));
        Person person2 = (Person)person.clone();
        //深拷贝操作
        person2.location = (Location) person.location.clone();
        System.out.println(person == person2);
        person.location.name = "sh";
        System.out.println(person2.location.name);

    }
}

class Person implements Cloneable{

    int age;
    int score;

    Location location;

    public Person(int age, int score, Location location) {
        this.age = age;
        this.score = score;
        this.location = location;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", score=" + score +
                ", location=" + location +
                '}';
    }
}


class Location implements Cloneable{
    String name;

    int doorNo;

    public Location(String name, int doorNo) {
        this.name = name;
        this.doorNo = doorNo;
    }

    @Override
    public String toString() {
        return "Location{" +
                "name='" + name + '\'' +
                ", doorNo=" + doorNo +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}